using Microsoft.Extensions.Logging;
using Vin.Extension.LoggerNotify.Options;
using Vin.Extension.LoggerNotify.Tools;
using Vin.Extension.Notify.QiyeWechat.Service;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.AssertCategory;
using Vin.Tool.Core.BasicTypeCategory;
using Vin.Tool.Core.ExceptionCategory;

namespace Vin.Extension.LoggerNotify.Logger.QiyeWechat;

public class QiyeWechatLogger : BaseLogger
{
    private QwSendMsgService? SendMsgService => VinApp.GetService<QwSendMsgService>();

    private QiyeWechatOption QiyeWechatOption => VinApp.GetConfig<QiyeWechatOption>();

    private List<LogLevel> ReceiveLevels => QiyeWechatOption.ReceiveLevels.Count > 0
        ? QiyeWechatOption.ReceiveLevels
        : new List<LogLevel> { LogLevel.Error, LogLevel.Critical };

    public override void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
        Func<TState, Exception?, string> formatter)
    {
        if (SendMsgService == null || QiyeWechatOption.Enable == false || !CheckIsNotify(logLevel) ||
            !CheckIsNotify(exception) ||
            (QiyeWechatOption.Senders.Count == 0 && QiyeWechatOption.LevelSenders.Count == 0)) return;
        var (title, message, requestId) =
            NotifyTool.RegexMessage(exception.ExceptionMessage(), Option.TitleRegex, Option.TitleLength);

        message = message.Substring(0, message.Length > 500 ? 500 : message.Length);
        var defaultContent = $"> 运行应用：<font color=\"warning\">{VinApp.WebHostEnvironment.ApplicationName}</font>\n" +
                             $"> 运行环境：<font color=\"warning\">{VinApp.WebHostEnvironment.EnvironmentName}</font>\n" +
                             $"> 日志等级：<font color=\"warning\">{logLevel.ToString()}</font>\n" +
                             $"> 日志标题：{title}\n" +
                             $"> 日志内容：{message}\n" +
                             $"> 请求ID：{requestId}\n";
        var content = (QiyeWechatOption.Prefix.IsNotNullOrEmpty() ? $"{QiyeWechatOption.Prefix}\n" : "") +
                      (QiyeWechatOption.Content.IsNotNullOrEmpty()
                          ? $"{QiyeWechatOption.Content.Format(new
                          {
                              LogLevel = logLevel.ToString(),
                              Title = title,
                              Message = message,
                              RequestId = requestId,
                              DefaultContent = defaultContent,
                              VinApp.WebHostEnvironment.EnvironmentName
                          })}\n"
                          : defaultContent) +
                      (QiyeWechatOption.Suffix.IsNotNullOrEmpty() ? $"{QiyeWechatOption.Suffix}\n" : "");

        var senders = QiyeWechatOption.Senders;
        if (QiyeWechatOption.LevelSenders.ContainsKey(logLevel))
        {
            senders = QiyeWechatOption.LevelSenders[logLevel];
        }

        if (senders.Count > 0)
        {
            foreach (var sender in senders)
            {
                _ = SendMsgService.SendMarkdownMessageAsync(sender, content,
                    ReceiveLevels.Contains(logLevel) ? QiyeWechatOption.Receivers : new List<string>()).Result;
            }
        }
    }
}